using System;
using System.Threading;
using System.IO;
using System.Collections;

namespace WPChanger
{
	/// <summary>
	/// Summary description for WPCache.
	/// </summary>
	public class WPCache
	{
		private static ArrayList _WPList = new ArrayList();
		private string _PatternMatch = "";
		private string _Dir = "";

		/// <summary>
		/// Create a new Cache starting with the specified directory
		/// </summary>
		/// <param name="dir"></param>
		public WPCache(string dir, string patternMatch)
		{
			_Dir = dir;
			_PatternMatch = patternMatch;
			fillArrayList();
			//getDirsWP(new DirectoryInfo(dir),true);
		}

		/// <summary>
		/// Clear the cache and begin a new search
		/// </summary>
		/// <param name="dir"></param>
		public void changeWPDir(string dir)
		{
			this.clearWPCache();
			_Dir = dir;
			fillArrayList();
			//getDirsWP(new DirectoryInfo(dir),true);
		}

		/// <summary>
		/// Return the list of collected wallpapers 
		/// </summary>
		/// <returns></returns>
		public ArrayList getWPs()
		{
			return _WPList;
		}

		/// <summary>
		/// Clear the cache
		/// </summary>
		private void clearWPCache()
		{
			_WPList = new ArrayList();
		}

		private void fillArrayList()
		{
			FillAL.Dir = _Dir;
			FillAL.PatternMatch = _PatternMatch;
			Thread thread1 = new Thread(new ThreadStart(FillAL.getDirsWP)); 
			thread1.Start();
		}

		/// <summary>
		/// Recursively search for files through directories and subdirectories
		/// </summary>
		/// <param name="curDir"></param>
		/// <param name="recursive"></param>
		/*private void getDirsWP(DirectoryInfo curDir, bool recursive)
		{
			FileInfo [] files = curDir.GetFiles("*.*");

			foreach (FileInfo file in files)
			{
				_WPList.Add(file.FullName);
			}
            
			if (recursive == true)
			{
				DirectoryInfo [] dirs = curDir.GetDirectories(_PatternMatch);          
				foreach (DirectoryInfo dir in dirs)
				{
					getDirsWP(dir,true);
				}
			}
		}*/

		class FillAL
		{
			public static string Dir = "";
			public static bool Recursive = true;
			public static string PatternMatch = "*.*";

			public FillAL(){}
			public static void getDirsWP()
			{
				if (Directory.Exists(Dir))
				{
					getDirsWP(new DirectoryInfo(Dir),Recursive);
				}
			}

			private static void getDirsWP(DirectoryInfo curDir, bool recursive)
			{
				FileInfo [] files = curDir.GetFiles("*.*");

				foreach (FileInfo file in files)
				{
					_WPList.Add(file.FullName);
					//System.Diagnostics.Debug.WriteLine(file.FullName);
				}
            
				if (recursive == true)
				{
					DirectoryInfo [] dirs = curDir.GetDirectories(PatternMatch);          
					foreach (DirectoryInfo dir in dirs)
					{
						getDirsWP(dir,true);
					}
				}
			}
		}
	}
}
